<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？ | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="今天我们来学习 Kotlin 协程的 select。 select，在目前的 Kotlin 1.6 当中，仍然是一个实验性的特性（Experimental）。但是，考虑到 select 具有较强的实用性，我决定还是来给你介绍一下它。 select 可以说是软件架构当中非常重要的一个组件，在很多业务场景下，select 与 Deferred、Channel 结合以后，在大大提升程序的响应速度的同时">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？">
<meta property="og:url" content="https://devsu.top/posts/4b3d9f4d/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="今天我们来学习 Kotlin 协程的 select。 select，在目前的 Kotlin 1.6 当中，仍然是一个实验性的特性（Experimental）。但是，考虑到 select 具有较强的实用性，我决定还是来给你介绍一下它。 select 可以说是软件架构当中非常重要的一个组件，在很多业务场景下，select 与 Deferred、Channel 结合以后，在大大提升程序的响应速度的同时">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://pic.rmb.bdstatic.com/66c29f8df73f201a1b3f3f1661ccf957.jpeg">
<meta property="article:published_time" content="2022-06-01T02:13:38.000Z">
<meta property="article:modified_time" content="2023-03-23T07:58:25.136Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Kotlin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://pic.rmb.bdstatic.com/66c29f8df73f201a1b3f3f1661ccf957.jpeg"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/4b3d9f4d/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-23 15:58:25'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://pic.rmb.bdstatic.com/66c29f8df73f201a1b3f3f1661ccf957.jpeg')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-06-01T02:13:38.000Z" title="发表于 2022-06-01 10:13:38">2022-06-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-23T07:58:25.136Z" title="更新于 2023-03-23 15:58:25">2023-03-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/">Kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/Kotlin%E7%BC%96%E7%A8%8B%E7%AC%AC%E4%B8%80%E8%AF%BE/">Kotlin编程第一课</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>19分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><audio id="audioPlayer" controlslist="nodownload" controls="" src="https://github.com/winstone-su/imageHosting/blob/main/course/kotlin/kotlin-programming-first-lesson/21%20_%20select%EF%BC%9A%E5%88%B0%E5%BA%95%E6%98%AF%E5%9C%A8%E9%80%89%E6%8B%A9%E4%BB%80%E4%B9%88%EF%BC%9F-%E6%9E%81%E5%AE%A2%E6%97%B6%E9%97%B4.mp3?raw=true" style="position: relative; width: 565px; height: 54px; left: 0px; top: 0px;"></audio></p>
<p>今天我们来学习 Kotlin 协程的 select。</p>
<p>select，在目前的 Kotlin 1.6 当中，仍然是一个<strong>实验性的特性</strong>（Experimental）。但是，考虑到 select 具有较强的实用性，我决定还是来给你介绍一下它。</p>
<p>select 可以说是软件架构当中非常重要的一个组件，在很多业务场景下，select 与 Deferred、Channel 结合以后，在大大提升程序的响应速度的同时，还可以提高程序的灵活性、扩展性。</p>
<p>今天这节课，我会从 select 的<strong>使用角度</strong>着手，带你理解 select 的核心使用场景，之后也会通过源码帮你进一步分析 select API 的底层规律。学完这节课以后，你完全可以将 select 应用到自己的工作当中去。</p>
<p>好，接下来，我们就一起来学习 select 吧！</p>
<h3>select 就是选择“更快的结果”</h3>

<p>由于 select 的工作机制比较抽象，我们先来假设一个场景，看看 select 适用于什么样的场景。</p>
<p>客户端，想要查询一个商品的详情。目前有两个服务：缓存服务，速度快但信息可能是旧的；网络服务，速度慢但信息一定是最新的。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/50/86/50f7c90d8a01e42834500bb5yy705486.jpg?wh=1576x707" alt="img"></p>
<p>对于这个场景，如果让我们来实现其中的逻辑的话，我们非常轻松地就能实现类似这样的代码逻辑：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段1</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getCacheInfo</span><span class="params">(productId: <span class="type">String</span>)</span></span>: Product? &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        <span class="keyword">return</span> Product(productId, <span class="number">9.9</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getNetworkInfo</span><span class="params">(productId: <span class="type">String</span>)</span></span>: Product? &#123;</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        <span class="keyword">return</span> Product(productId, <span class="number">9.8</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">updateUI</span><span class="params">(product: <span class="type">Product</span>)</span></span> &#123;</span><br><span class="line">        println(<span class="string">&quot;<span class="subst">$&#123;product.productId&#125;</span>==<span class="subst">$&#123;product.price&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> productId = <span class="string">&quot;xxxId&quot;</span></span><br><span class="line">    <span class="comment">// 查询缓存</span></span><br><span class="line">    <span class="keyword">val</span> cacheInfo = getCacheInfo(productId)</span><br><span class="line">    <span class="keyword">if</span> (cacheInfo != <span class="literal">null</span>) &#123;</span><br><span class="line">        updateUI(cacheInfo)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 查询网络</span></span><br><span class="line">    <span class="keyword">val</span> latestInfo = getNetworkInfo(productId)</span><br><span class="line">    <span class="keyword">if</span> (latestInfo != <span class="literal">null</span>) &#123;</span><br><span class="line">        updateUI(latestInfo)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">data</span> <span class="keyword">class</span> <span class="title class_">Product</span>(</span><br><span class="line">    <span class="keyword">val</span> productId: String,</span><br><span class="line">    <span class="keyword">val</span> price: <span class="built_in">Double</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">xxxId==9.9</span></span><br><span class="line"><span class="comment">Time cost: 112</span></span><br><span class="line"><span class="comment">xxxId==9.8</span></span><br><span class="line"><span class="comment">Time cost: 314</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>考虑到缓存服务速度更快，我们自然而然会这么写，先去查询缓存服务，如果查询到了信息，我们就会去更新 UI 界面。之后去查询网络服务，拿到最新的信息之后，我们再来更新 UI 界面。也就是这样：</p>
<ul>
<li>第一步：查询缓存信息；</li>
<li>第二步：缓存服务返回信息，更新 UI；</li>
<li>第三步：查询网络服务；</li>
<li>第四步：网络服务返回信息，更新 UI。</li>
</ul>
<p>这种做法的好处在于，用户可以第一时间看到商品的信息，虽然它暂时会展示旧的信息，但由于我们同时查询了网络服务，旧缓存信息也马上会被替代成新的信息。这样的做法，可以最大程度保证用户体验。</p>
<p>不过，以上整个流程都是建立在“缓存服务一定更快”的前提下的，万一我们的缓存服务出了问题，它的速度变慢了，甚至是超时、无响应呢？</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/12/b1/1267b73837eaa9370651e468c1c536b1.jpg?wh=1607x717" alt="img"></p>
<p>这时候，如果你回过头来分析代码段 1 的话，你就会发现：程序执行流程会卡在第二步，迟迟无法进行第三步。具体来说，是因为 getCacheInfo() 它是一个挂起函数，只有这个程序执行成功以后，才可以继续执行后面的任务。你也可以把 getCacheInfo() 当中的 delay 时间修改成 2000 毫秒，去验证一下。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">执行结果：</span></span><br><span class="line"><span class="comment">xxxId==9.9</span></span><br><span class="line"><span class="comment">Time cost: 2013</span></span><br><span class="line"><span class="comment">xxxId==9.8</span></span><br><span class="line"><span class="comment">Time cost: 2214</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>那么，面对这样的场景，我们其实需要一个可以灵活选择的语法：“两个挂起函数同时执行，谁返回的速度更快，我们就选择谁”。这其实就是 select 的典型使用场景。</p>
<h2 id="select-和-async"><a href="#select-和-async" class="headerlink" title="select 和 async"></a>select 和 async</h2><p>上面的这个场景，我们可以用 async 搭配 select 来使用。async 可以实现并发，select 则可以选择最快的结果。</p>
<p>让我们来看看，代码具体该怎么写。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段2</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> productId = <span class="string">&quot;xxxId&quot;</span></span><br><span class="line">    <span class="comment">//          1，注意这里</span></span><br><span class="line">    <span class="comment">//               ↓</span></span><br><span class="line">    <span class="keyword">val</span> product = select&lt;Product?&gt; &#123;</span><br><span class="line">        <span class="comment">// 2，注意这里</span></span><br><span class="line">        async &#123; getCacheInfo(productId) &#125;</span><br><span class="line">            .onAwait &#123; <span class="comment">// 3，注意这里</span></span><br><span class="line">                it</span><br><span class="line">            &#125;</span><br><span class="line">        <span class="comment">// 4，注意这里</span></span><br><span class="line">        async &#123; getNetworkInfo(productId) &#125;</span><br><span class="line">            .onAwait &#123;  <span class="comment">// 5，注意这里</span></span><br><span class="line">                it</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (product != <span class="literal">null</span>) &#123;</span><br><span class="line">        updateUI(product)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">xxxId==9.9</span></span><br><span class="line"><span class="comment">Time cost: 127</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>从上面的执行结果，我们可以看到，由于缓存的服务更快，所以，select 确实帮我们选择了更快的那个结果。代码中一共有四个注释，我们一起来看看：</p>
<ul>
<li>注释 1，我们使用 select 这个高阶函数包裹了两次查询的服务，同时传入了泛型参数 Product，代表我们要选择的数据类型是 Product。</li>
<li>注释 2，4 中，我们使用了 async 包裹了 getCacheInfo()、getNetworkInfo() 这两个挂起函数，这是为了让这两个查询实现并发执行。</li>
<li>注释 3，5 中，我们使用 onAwait{} 将执行结果传给了 select{}，而 select 才能进一步将数据返回给 product 局部变量。<strong>注意了，这里我们用的 onAwait{}，而不是 await()。</strong></li>
</ul>
<p>现在，假设，我们的缓存服务出现了问题，需要 2000 毫秒才能返回：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段3</span></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getCacheInfo</span><span class="params">(productId: <span class="type">String</span>)</span></span>: Product? &#123;</span><br><span class="line">    <span class="comment">// 注意这里</span></span><br><span class="line">    delay(<span class="number">2000L</span>)</span><br><span class="line">    <span class="keyword">return</span> Product(productId, <span class="number">9.9</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">xxxId==9.8</span></span><br><span class="line"><span class="comment">Time cost: 226</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这时候，通过执行结果，我们可以发现，我们的 select 可以在缓存服务出现问题的时候，灵活选择网络服务的结果。从而避免用户等待太长的时间，得到糟糕的体验。</p>
<p>不过，你也许发现了，“代码段 1”和“代码段 2”其实并不是完全等价的。因为在代码段 2 当中，用户大概率是会展示旧的缓存信息。但实际场景下，我们是需要进一步更新最新信息的。</p>
<p>其实，在代码段 2 的基础上，我们也可以轻松实现，只是说，这里我们需要为 Product 这个数据类增加一个标记。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段4</span></span><br><span class="line"><span class="keyword">data</span> <span class="keyword">class</span> <span class="title class_">Product</span>(</span><br><span class="line">    <span class="keyword">val</span> productId: String,</span><br><span class="line">    <span class="keyword">val</span> price: <span class="built_in">Double</span>,</span><br><span class="line">    <span class="comment">// 是不是缓存信息</span></span><br><span class="line">    <span class="keyword">val</span> isCache: <span class="built_in">Boolean</span> = <span class="literal">false</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>然后，我们还需要对代码段 2 的逻辑进行一些提取：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段5</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getCacheInfo</span><span class="params">(productId: <span class="type">String</span>)</span></span>: Product? &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        <span class="keyword">return</span> Product(productId, <span class="number">9.9</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getNetworkInfo</span><span class="params">(productId: <span class="type">String</span>)</span></span>: Product? &#123;</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        <span class="keyword">return</span> Product(productId, <span class="number">9.8</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">updateUI</span><span class="params">(product: <span class="type">Product</span>)</span></span> &#123;</span><br><span class="line">        println(<span class="string">&quot;<span class="subst">$&#123;product.productId&#125;</span>==<span class="subst">$&#123;product.price&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> productId = <span class="string">&quot;xxxId&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 1，缓存和网络，并发执行</span></span><br><span class="line">    <span class="keyword">val</span> cacheDeferred = async &#123; getCacheInfo(productId) &#125;</span><br><span class="line">    <span class="keyword">val</span> latestDeferred = async &#123; getNetworkInfo(productId) &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2，在缓存和网络中间，选择最快的结果</span></span><br><span class="line">    <span class="keyword">val</span> product = select&lt;Product?&gt; &#123;</span><br><span class="line">        cacheDeferred.onAwait &#123;</span><br><span class="line">                it?.copy(isCache = <span class="literal">true</span>)</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        latestDeferred.onAwait &#123;</span><br><span class="line">                it?.copy(isCache = <span class="literal">false</span>)</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3，更新UI</span></span><br><span class="line">    <span class="keyword">if</span> (product != <span class="literal">null</span>) &#123;</span><br><span class="line">        updateUI(product)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 4，如果当前结果是缓存，那么再取最新的网络服务结果</span></span><br><span class="line">    <span class="keyword">if</span> (product != <span class="literal">null</span> &amp;&amp; product.isCache) &#123;</span><br><span class="line">        <span class="keyword">val</span> latest = latestDeferred.await()?: <span class="keyword">return</span><span class="symbol">@runBlocking</span></span><br><span class="line">        updateUI(latest)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">xxxId==9.9</span></span><br><span class="line"><span class="comment">Time cost: 120</span></span><br><span class="line"><span class="comment">xxxId==9.8</span></span><br><span class="line"><span class="comment">Time cost: 220</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>如果你对比代码段 1 和代码段 5 的执行结果，会发现代码段 5 的总体耗时更短。</p>
<p>另外在上面的代码中，还有几个注释，我们一个个看：</p>
<ul>
<li>首先看注释 1，我们将 getCacheInfo()、getNetworkInfo() 提取到了 select 的外部，让它们通过 async 并发执行。如果你还记得第 16 讲思考题当中的逻辑，你一定可以理解这里的 async 并发。（如果你忘了，可以回过头去看看。）</li>
<li>注释 2，我们仍然是通过 select 选择最快的那个结果，接着在注释 3 这里我们第一时间更新 UI 界面。</li>
<li>注释 4，我们判断当前的 product 是不是来自于缓存，如果是的话，我们还需要用最新的信息更新 UI。</li>
</ul>
<p>然后在这里，假设我们的缓存服务出现了问题，需要 2000 毫秒才能返回：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段6</span></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">getCacheInfo</span><span class="params">(productId: <span class="type">String</span>)</span></span>: Product? &#123;</span><br><span class="line">    <span class="comment">// 注意这里</span></span><br><span class="line">    delay(<span class="number">2000L</span>)</span><br><span class="line">    <span class="keyword">return</span> Product(productId, <span class="number">9.9</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">xxxId==9.8</span></span><br><span class="line"><span class="comment">Time cost: 224</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，代码仍然可以正常执行。其实，当前的这个例子很简单，不使用 select 同样也可以实现。不过，select 这样的代码模式的优势在于，<strong>扩展性非常好。</strong></p>
<p>下面，我们可以再来假设一下，现在我们有了多个缓存服务。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/dy/2b/dyydce7b6a709e2725bbffec9726312b.jpg?wh=1550x736" alt="img"></p>
<p>对于这个问题，我们其实只需要稍微改动一下代码段 3 就行了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段7</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> productId = <span class="string">&quot;xxxId&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> cacheDeferred = async &#123; getCacheInfo(productId) &#125;</span><br><span class="line">    <span class="comment">// 变化在这里</span></span><br><span class="line">    <span class="keyword">val</span> cacheDeferred2 = async &#123; getCacheInfo2(productId) &#125;</span><br><span class="line">    <span class="keyword">val</span> latestDeferred = async &#123; getNetworkInfo(productId) &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> product = select&lt;Product?&gt; &#123;</span><br><span class="line">        cacheDeferred.onAwait &#123;</span><br><span class="line">            it?.copy(isCache = <span class="literal">true</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 变化在这里</span></span><br><span class="line">        cacheDeferred2.onAwait &#123;</span><br><span class="line">            it?.copy(isCache = <span class="literal">true</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        latestDeferred.onAwait &#123;</span><br><span class="line">            it?.copy(isCache = <span class="literal">false</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (product != <span class="literal">null</span>) &#123;</span><br><span class="line">        updateUI(product)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (product != <span class="literal">null</span> &amp;&amp; product.isCache) &#123;</span><br><span class="line">        <span class="keyword">val</span> latest = latestDeferred.await() ?: <span class="keyword">return</span><span class="symbol">@runBlocking</span></span><br><span class="line">        updateUI(latest)</span><br><span class="line">        println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">xxxId==9.9</span></span><br><span class="line"><span class="comment">Time cost: 125</span></span><br><span class="line"><span class="comment">xxxId==9.8</span></span><br><span class="line"><span class="comment">Time cost: 232</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，当增加一个缓存服务进来的时候，我们的代码只需要做很小的改动，就可以实现。</p>
<p>所以，总的来说，对比传统的挂起函数串行的执行流程，select 这样的代码模式，不仅可以提升程序的整体响应速度，还可以大大提升程序的<strong>灵活性、扩展性</strong>。</p>
<h2 id="select-和-Channel"><a href="#select-和-Channel" class="headerlink" title="select 和 Channel"></a>select 和 Channel</h2><p>在前面的课程我们提到过，在协程中返回一个内容的时候，我们可以使用挂起函数、async，但如果要返回多个结果的话，就要用 Channel 和 Flow。</p>
<p>那么，这里我们来看看 select 和 Channel 的搭配使用。这里，我们有两个管道，channel1、channel2，它们里面的内容分别是 1、2、3；a、b、c，我们通过 select，将它们当中的数据收集出来并打印。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/d2/e4/d2d280yy62f88e03522a435b3abyy9e4.gif?wh=1080x608" alt="img"></p>
<p>对于这个问题，如果我们不借助 select 来实现的话，其实可以大致做到，但结果不会令人满意。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段8</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> channel1 = produce &#123;</span><br><span class="line">        send(<span class="number">1</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="number">2</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="number">3</span>)</span><br><span class="line">        delay(<span class="number">150L</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> channel2 = produce &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        send(<span class="string">&quot;a&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;b&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;c&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    channel1.consumeEach &#123;</span><br><span class="line">        println(it)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    channel2.consumeEach &#123;</span><br><span class="line">        println(it)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">1</span></span><br><span class="line"><span class="comment">2</span></span><br><span class="line"><span class="comment">3</span></span><br><span class="line"><span class="comment">a</span></span><br><span class="line"><span class="comment">b</span></span><br><span class="line"><span class="comment">c</span></span><br><span class="line"><span class="comment">Time cost: 989</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，通过普通的方式，我们的代码是串行执行的，执行结果并不符合预期。channel1 执行完毕以后，才会执行 channel2，程序总体的执行时间，也是两者的总和。最关键的是，如果 channel1 当中如果迟迟没有数据的话，我们的程序会一直卡着不执行。</p>
<p>当然，以上的问题，我们通过其他方式也可以解决，但最方便的解决方案，还是 select。让我们来看看 select 与 Channel 搭配后，会带来什么样的好处。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段9</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> channel1 = produce &#123;</span><br><span class="line">        send(<span class="string">&quot;1&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;2&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;3&quot;</span>)</span><br><span class="line">        delay(<span class="number">150L</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> channel2 = produce &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        send(<span class="string">&quot;a&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;b&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;c&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">selectChannel</span><span class="params">(channel1: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;, channel2: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;)</span></span>: String = select&lt;String&gt; &#123;</span><br><span class="line">        <span class="comment">// 1， 选择channel1</span></span><br><span class="line">        channel1.onReceive&#123;</span><br><span class="line">            it.also &#123; println(it) &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 2， 选择channel1</span></span><br><span class="line">        channel2.onReceive&#123;</span><br><span class="line">            it.also &#123; println(it) &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    repeat(<span class="number">6</span>)&#123;<span class="comment">// 3， 选择6次结果</span></span><br><span class="line">        selectChannel(channel1, channel2)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">1</span></span><br><span class="line"><span class="comment">a</span></span><br><span class="line"><span class="comment">2</span></span><br><span class="line"><span class="comment">b</span></span><br><span class="line"><span class="comment">3</span></span><br><span class="line"><span class="comment">c</span></span><br><span class="line"><span class="comment">Time cost: 540</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>从程序的执行结果中，我们可以看到，程序的输出结果符合预期，同时它的执行耗时，也比代码段 8 要少很多。上面的代码中有几个注释，我们来看看：</p>
<ul>
<li>注释 1 和 2，onReceive{} 是 Channel 在 select 当中的语法，当 Channel 当中有数据以后，它就会被回调，通过这个 Lambda，我们也可以将结果传出去。</li>
<li>注释 3，这里我们执行了 6 次 select，目的是要把两个管道中的所有数据都消耗掉。管道 1 有 3 个数据、管道 2 有 3 个数据，所以加起来，我们需要选择 6 次。</li>
</ul>
<p>这时候，假设 channel1 出了问题，它不再产生数据了，我们看看程序会怎么样执行。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段10</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> channel1 = produce&lt;String&gt; &#123;</span><br><span class="line">        <span class="comment">// 变化在这里</span></span><br><span class="line">        delay(<span class="number">15000L</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> channel2 = produce &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        send(<span class="string">&quot;a&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;b&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;c&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">selectChannel</span><span class="params">(channel1: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;, channel2: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;)</span></span>: String = select&lt;String&gt; &#123;</span><br><span class="line">        channel1.onReceive&#123;</span><br><span class="line">            it.also &#123; println(it) &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        channel2.onReceive&#123;</span><br><span class="line">            it.also &#123; println(it) &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 变化在这里</span></span><br><span class="line">    repeat(<span class="number">3</span>)&#123;</span><br><span class="line">        selectChannel(channel1, channel2)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">a</span></span><br><span class="line"><span class="comment">b</span></span><br><span class="line"><span class="comment">c</span></span><br><span class="line"><span class="comment">Time cost: 533</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们将 channel1 当中的 send() 都删除了，并且，repeat() 的次数变成了 3 次，因为管道里只有三个数据了。</p>
<p>这时候，我们发现，select 也是可以正常执行的。</p>
<p>不过，我们有时候可能并不清楚每个 Channel 当中有多少个数据，比如说，这里如果我们还是写 repeat(6) 的话，程序就会出问题了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段11</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 仅改动这里</span></span><br><span class="line">repeat(<span class="number">6</span>)&#123;</span><br><span class="line">    selectChannel(channel1, channel2)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">崩溃：</span></span><br><span class="line"><span class="comment">Exception in thread &quot;main&quot; ClosedReceiveChannelException: Channel was closed</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这时候，你应该就能反应过来了，由于我们的 channel2 当中只有 3 个数据，它发送完数据以后就会被关闭，而我们的 select 是会被调用 6 次的，所以就会触发上面的 ClosedReceiveChannelException 异常。</p>
<p>在 19 讲当中，我们学过 receiveCatching() 这个方法，它可以封装 Channel 的结果，防止出现 ClosedReceiveChannelException。类似的，当 Channel 与 select 配合的时候，我们可以使用 onReceiveCatching{} 这个高阶函数。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段12</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> channel1 = produce&lt;String&gt; &#123;</span><br><span class="line">        delay(<span class="number">15000L</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> channel2 = produce &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        send(<span class="string">&quot;a&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;b&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;c&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">selectChannel</span><span class="params">(channel1: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;, channel2: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;)</span></span>: String =</span><br><span class="line">        select&lt;String&gt; &#123;</span><br><span class="line">            channel1.onReceiveCatching &#123;</span><br><span class="line">                it.getOrNull() ?: <span class="string">&quot;channel1 is closed!&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">            channel2.onReceiveCatching &#123;</span><br><span class="line">                it.getOrNull() ?: <span class="string">&quot;channel2 is closed!&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    repeat(<span class="number">6</span>) &#123;</span><br><span class="line">        <span class="keyword">val</span> result = selectChannel(channel1, channel2)</span><br><span class="line">        println(result)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">a</span></span><br><span class="line"><span class="comment">b</span></span><br><span class="line"><span class="comment">c</span></span><br><span class="line"><span class="comment">channel2 is closed!</span></span><br><span class="line"><span class="comment">channel2 is closed!</span></span><br><span class="line"><span class="comment">channel2 is closed!</span></span><br><span class="line"><span class="comment">Time cost: 541</span></span><br><span class="line"><span class="comment">程序不会立即退出</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这时候，即使我们不知道管道里有多少个数据，我们也不用担心崩溃的问题了。在 onReceiveCatching{} 这个高阶函数当中，我们可以使用 it.getOrNull() 来获取管道里的数据，如果获取的结果是 null，就代表管道已经被关闭了。</p>
<p>不过，上面的代码仍然还有一个问题，那就是，当我们得到所有结果以后，程序不会立即退出，因为我们的 channel1 一直在 delay()。这时候，当我们完成 6 次 repeat() 调用以后，我们将 channel1、channel2 取消即可。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段13</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> startTime = System.currentTimeMillis()</span><br><span class="line">    <span class="keyword">val</span> channel1 = produce&lt;String&gt; &#123;</span><br><span class="line">        delay(<span class="number">15000L</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> channel2 = produce &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        send(<span class="string">&quot;a&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;b&quot;</span>)</span><br><span class="line">        delay(<span class="number">200L</span>)</span><br><span class="line">        send(<span class="string">&quot;c&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">selectChannel</span><span class="params">(channel1: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;, channel2: <span class="type">ReceiveChannel</span>&lt;<span class="type">String</span>&gt;)</span></span>: String =</span><br><span class="line">        select&lt;String&gt; &#123;</span><br><span class="line">            channel1.onReceiveCatching &#123;</span><br><span class="line">                it.getOrNull() ?: <span class="string">&quot;channel1 is closed!&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">            channel2.onReceiveCatching &#123;</span><br><span class="line">                it.getOrNull() ?: <span class="string">&quot;channel2 is closed!&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    repeat(<span class="number">6</span>) &#123;</span><br><span class="line">        <span class="keyword">val</span> result = selectChannel(channel1, channel2)</span><br><span class="line">        println(result)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 变化在这里</span></span><br><span class="line">    channel1.cancel()</span><br><span class="line">    channel2.cancel()</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;Time cost: <span class="subst">$&#123;System.currentTimeMillis() - startTime&#125;</span>&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这时候，我们对比一下代码段 13 和代码段 10 的话，就会发现程序的执行效率提升的同时，扩展性和灵活性也更好了。</p>
<p><code>提示：这种将多路数据以非阻塞的方式合并成一路数据的模式，在其他领域也有广泛的应用，比如说操作系统、Java NIO（Non-blocking I/O），等等。如果你能理解这个案例中的代码，相信你对操作系统、NIO 之类的技术也会有一个新的认识。</code></p>
<h2 id="思考与实战"><a href="#思考与实战" class="headerlink" title="思考与实战"></a>思考与实战</h2><p>如果你足够细心的话，你会发现，当我们的 Deferred、Channel 与 select 配合的时候，它们原本的 API 会多一个 on 前缀。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Deferred</span> : <span class="type">CoroutineContext.Element</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">join</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">await</span><span class="params">()</span></span>: T</span><br><span class="line"></span><br><span class="line">    <span class="comment">// select相关  </span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> onJoin: SelectClause0</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> onAwait: SelectClause1&lt;T&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">SendChannel</span>&lt;<span class="type">in E</span>&gt; </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">send</span><span class="params">(element: <span class="type">E</span>)</span></span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// select相关</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> onSend: SelectClause2&lt;E, SendChannel&lt;E&gt;&gt;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">ReceiveChannel</span>&lt;<span class="type">out E</span>&gt; &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">receive</span><span class="params">()</span></span>: E</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">receiveCatching</span><span class="params">()</span></span>: ChannelResult&lt;E&gt;</span><br><span class="line">    <span class="comment">// select相关</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> onReceive: SelectClause1&lt;E&gt;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">val</span> onReceiveCatching: SelectClause1&lt;ChannelResult&lt;E&gt;&gt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以，只要你记住了 Deferred、Channel 的 API，你是不需要额外记忆 select 的 API 的，只需要在原本的 API 的前面加上一个 on 就行了。</p>
<p>另外你要注意，当 select 与 Deferred 结合使用的时候，当并行的 Deferred 比较多的时候，你往往需要在得到一个最快的结果以后，去取消其他的 Deferred。</p>
<p>比如说，对于 Deferred1、Deferred2、Deferred3、Deferred4、Deferred5，其中 Deferred2 返回的结果最快，这时候，我们往往会希望取消其他的 Deferred，以节省资源。那么在这个时候，我们可以使用类似这样的方式：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T&gt;</span> <span class="title">fastest</span><span class="params">(<span class="keyword">vararg</span> deferreds: <span class="type">Deferred</span>&lt;<span class="type">T</span>&gt;)</span></span>: T = select &#123;</span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">cancelAll</span><span class="params">()</span></span> = deferreds.forEach &#123; it.cancel() &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (deferred <span class="keyword">in</span> deferreds) &#123;</span><br><span class="line">            deferred.onAwait &#123;</span><br><span class="line">                cancelAll()</span><br><span class="line">                it</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> deferred1 = async &#123;</span><br><span class="line">        delay(<span class="number">100L</span>)</span><br><span class="line">        println(<span class="string">&quot;done1&quot;</span>)    <span class="comment">// 没机会执行</span></span><br><span class="line">        <span class="string">&quot;result1&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> deferred2 = async &#123;</span><br><span class="line">        delay(<span class="number">50L</span>)</span><br><span class="line">        println(<span class="string">&quot;done2&quot;</span>)</span><br><span class="line">        <span class="string">&quot;result2&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> deferred3 = async &#123;</span><br><span class="line">        delay(<span class="number">10000L</span>)</span><br><span class="line">        println(<span class="string">&quot;done3&quot;</span>)    <span class="comment">// 没机会执行</span></span><br><span class="line">        <span class="string">&quot;result3&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> deferred4 = async &#123;</span><br><span class="line">        delay(<span class="number">2000L</span>)</span><br><span class="line">        println(<span class="string">&quot;done4&quot;</span>)    <span class="comment">// 没机会执行</span></span><br><span class="line">        <span class="string">&quot;result4&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> deferred5 = async &#123;</span><br><span class="line">        delay(<span class="number">14000L</span>)</span><br><span class="line">        println(<span class="string">&quot;done5&quot;</span>)    <span class="comment">// 没机会执行</span></span><br><span class="line">        <span class="string">&quot;result5&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> result = fastest(deferred1, deferred2, deferred3, deferred4, deferred5)</span><br><span class="line">    println(result)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">done2</span></span><br><span class="line"><span class="comment">result2</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>所以，借助这样的方式，我们不仅可以通过 async 并发执行协程，也可以借助 select 得到最快的结果，而且，还可以避免不必要的资源浪费。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>好，这节课的内容就到这儿了，我们来做一个简单的总结。</p>
<ul>
<li>select，就是选择“更快的结果”。</li>
<li>当 select 与 async、Channel 搭配以后，我们可以并发执行协程任务，以此大大提升程序的执行效率甚至用户体验，并且还可以改善程序的扩展性、灵活性。</li>
<li>关于 select 的 API，我们完全不需要去刻意记忆，只需要在 Deferred、Channel 的 API 基础上加上 on 这个前缀即可。</li>
<li>最后，我们还结合实战，分析了 select 与 async 产生太多并发协程的时候，还可以定义一个类似 fastest() 的方法，去统一取消剩余的协程任务。这样的做法，就可以大大节省计算资源，从而平衡性能与功耗。</li>
</ul>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/5c/5b/5c3e1e2b9e00c367e413428d40994f5b.jpg?wh=2000x853" alt="img"></p>
<p>其实，和 Kotlin 的 Channel 一样，select 并不是 Kotlin 独创的概念。select 在很多编程语言当中都有类似的实现，比如 Go、Rust，等等。在这些计算机语言当中，select 的语法可能与 Kotlin 的不太一样，但背后的核心理念都是“选择更快的结果”。</p>
<p>所以，只要你掌握了 Kotlin 的 select，今后学习其他编程语言的 select，都不再是问题。</p>
<h2 id="思考题"><a href="#思考题" class="headerlink" title="思考题"></a>思考题</h2><p>前面我们已经说过，select 的 API，只需要在 Deferred、Channel 原本 API 的基础上加一个 on 前缀即可。比如 onAwait{}。那么，你有没有觉得它跟我们前面学的 onStart{}、onCompletion{} 之类的回调 API 很像？</p>
<p>你能从中悟出 select 的实现原理吗？ 欢迎在留言区说说你的想法，也欢迎你把今天的内容分享给更多的朋友。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/4b3d9f4d/">https://devsu.top/posts/4b3d9f4d/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Kotlin/">Kotlin</a></div><div class="post_share"><div class="social-share" data-image="https://pic.rmb.bdstatic.com/66c29f8df73f201a1b3f3f1661ccf957.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/778b5847/" title="Kotlin编程第一课--(协程篇)22  并发：协程不需要处理同步吗？"><img class="cover" src="https://img.tt98.com/d/file/pic/2018060523545938/5b15f4a3092f0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Kotlin编程第一课--(协程篇)22  并发：协程不需要处理同步吗？</div></div></a></div><div class="next-post pull-right"><a href="/posts/e7c23ba1/" title="Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？"><img class="cover" src="https://img1.baidu.com/it/u=4050062314,1116360005&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？"><img class="cover" src="https://static001.geekbang.org/resource/image/b6/1c/b65feyy0bdc4764c6564a95912d7851c.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-06</div><div class="title">Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？</div></div></a></div><div><a href="/posts/be9f17d6/" title="Kotlin编程第一课(目录)"><img class="cover" src="https://img2.baidu.com/it/u=3956021957,3313212296&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">Kotlin编程第一课(目录)</div></div></a></div><div><a href="/posts/83a7144c/" title="2023-01-17-Kotlin协程 -  结构化并发"><img class="cover" src="https://s2.loli.net/2023/03/14/xEyFgn24zZPXe15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-17</div><div class="title">2023-01-17-Kotlin协程 -  结构化并发</div></div></a></div><div><a href="/posts/68bf7d20/" title="Kotlin函数"><img class="cover" src="https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin函数</div></div></a></div><div><a href="/posts/a20c9e06/" title="Kotlin协程"><img class="cover" src="https://s2.loli.net/2023/03/14/3MHPBy1Q4GncRlF.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-09</div><div class="title">Kotlin协程</div></div></a></div><div><a href="/posts/8c331668/" title="Kotlin内置函数apply、let、run、with、also等区别"><img class="cover" src="https://s2.loli.net/2023/03/14/OpxWcuy2ktMzoQD.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin内置函数apply、let、run、with、also等区别</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">select 就是选择“更快的结果”</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#select-%E5%92%8C-async"><span class="toc-number"></span> <span class="toc-text">select 和 async</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#select-%E5%92%8C-Channel"><span class="toc-number"></span> <span class="toc-text">select 和 Channel</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E4%B8%8E%E5%AE%9E%E6%88%98"><span class="toc-number"></span> <span class="toc-text">思考与实战</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number"></span> <span class="toc-text">小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E9%A2%98"><span class="toc-number"></span> <span class="toc-text">思考题</span></a></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/4b3d9f4d/'
    this.page.identifier = '/posts/4b3d9f4d/'
    this.page.title = 'Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>